package com.hinnotek.warehouse.ui

import android.content.Intent
import android.graphics.Bitmap
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.KeyEvent
import android.webkit.*
import android.widget.LinearLayout
import androidx.activity.viewModels
import androidx.annotation.RequiresApi
import com.alibaba.android.arouter.facade.annotation.Route
import com.hinnotek.warehouse.R
import com.hinnotek.warehouse.databinding.ActivityWeb2Binding
import com.hinnotek.warehouse.utils.CustomSettings
import com.hinnotek.warehouse.viewmodel.WebViewModel
import com.just.agentweb.*
import com.just.agentweb.WebChromeClient
import com.just.agentweb.WebViewClient
import com.lee.common.base.BaseActivity
import com.lee.common.ext.getArg
import com.lee.common.utils.ACTIVITY_WEB2
import com.lee.common.utils.Skipping
import dagger.hilt.android.AndroidEntryPoint

/**
 * desripbe webView
 */
@Route(path = ACTIVITY_WEB2)
@AndroidEntryPoint
class Web2Activity : BaseActivity<ActivityWeb2Binding>() {

    private val viewModel by viewModels<WebViewModel>()
    var link = ""
    private var mAgentWeb: AgentWeb? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_web2)
        setTitle("详情")
        bindingView.vm = viewModel
        bindingView.executePendingBindings()
    }

    override fun initVew() {

        link = intent.getStringExtra("link") ?: ""
        mAgentWeb = AgentWeb.with(this)
            .setAgentWebParent(bindingView.container, LinearLayout.LayoutParams(-1, -1))
            .useDefaultIndicator()
            .setWebChromeClient(mWebChromeClient)
            .setWebViewClient(mWebViewClient)
            .setMainFrameErrorView(R.layout.agentweb_error_page, -1)
            .setSecurityType(AgentWeb.SecurityType.STRICT_CHECK)
            //.setWebLayout(WebLayout(this))
            .setOpenOtherPageWays(DefaultWebClient.OpenOtherPageWays.ASK)//打开其他应用时，弹窗咨询用户是否前往其他应用
            .interceptUnkownUrl() //拦截找不到相关页面的Scheme
            .setAgentWebWebSettings(CustomSettings(this))
            .createAgentWeb()
            .ready()
            .go(link)
    }

    override fun setData() {

    }

    private val mWebChromeClient = object : WebChromeClient() {
        override fun onReceivedTitle(view: WebView, title: String) {
            super.onReceivedTitle(view, title)
            setTitle(title)
        }
    }
    var num = 0 //控制wxUrl加载的次数
    private val firstVisitWXH5PayUrl = true

    private val mWebViewClient = object : WebViewClient() {

        @RequiresApi(Build.VERSION_CODES.N)
        override fun shouldOverrideUrlLoading(
            view: WebView?,
            request: WebResourceRequest?
        ): Boolean {
            Log.i("Info", "BaseWebActivity shouldOverrideUrlLoading coverUrl 2:${request!!.url}")

            val urlString = request?.url.toString()
            val isHttp = urlString.startsWith("http://") || urlString.startsWith("https://")
            return if (isHttp) {
                Skipping.navWeb(urlString, this@Web2Activity)
                true
            } else {
                true
            }

            return super.shouldOverrideUrlLoading(view, request)
        }

        override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
            Log.i("Info", "BaseWebActivity onPageStarted coverUrl:$url")
            super.onPageStarted(view, url, favicon)
        }

        override fun onPageFinished(view: WebView?, url: String?) {
            imgReset(view)
            viewModel.loaded.value = true
            super.onPageFinished(view, url)
        }
    }

    //返回监听
    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (mAgentWeb == null)
            return super.onKeyDown(keyCode, event);
        if (mAgentWeb!!.handleKeyEvent(keyCode, event)) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    override fun onPause() {
        mAgentWeb?.webLifeCycle!!.onPause()
        super.onPause()
    }

    override fun onResume() {
        mAgentWeb?.webLifeCycle!!.onResume()
        super.onResume()
    }

    override fun onDestroy() {
        super.onDestroy()
        mAgentWeb?.webLifeCycle!!.onDestroy()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        Log.i("Info", "onResult:$requestCode onResult:$resultCode")
        super.onActivityResult(requestCode, resultCode, data)
    }

    companion object {
        const val urlKey = "webUrl"
    }

    /**
     * 对图片进行重置大小，宽度就是手机屏幕宽度，高度根据宽度比便自动缩放
     **/
    private fun imgReset(view: WebView?) {
        mAgentWeb?.webCreator?.webView?.loadUrl(
            "javascript:(function(){" +
                    "var objs = document.getElementsByTagName('img'); " +
                    "for(var i=0;i<objs.length;i++) " +
                    "{"
                    + "var img = objs[i]; " +
                    " img.style.maxWidth = '100%'; img.style.height = 'auto'; " +
                    "}" +
                    "})()"
        );
    }


}